package com.zhouheng.common.security;

import com.zhouheng.common.constant.MenuConstants;
import com.zhouheng.module.dao.SysUserMapper;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * AuthenticationProvider(身份验证提供程序)：实现 security自定义身份认证验证组件
 *
 * @author 周恒
 * @date 20180831 15:55:57
 * @since v1.0
 */
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    private SysUserMapper sysUserMapper;

    public CustomAuthenticationProvider(UserDetailsService userDetailsService, SysUserMapper sysUserMapper) {
        this.userDetailsService = userDetailsService;
        this.sysUserMapper = sysUserMapper;
    }

    /**
     * 用户名密码校验，返回身份认证令牌
     *
     * @param authentication 身份验证令牌（其中包括用户名，密码，权限信息）
     * @author 周恒
     * @date 20200120 16:46:37
     * @since v1.0
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        System.out.println("CustomAuthenticationProvider.authenticate");
        // 获取认证的用户名 & 密码
        String userName = authentication.getName();
        String password = authentication.getCredentials().toString();
        //调用该接口我们现实了的认证方法
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        if (null != userDetails) {
            // 自定义的加密方法
            String encodePassword = DigestUtils.md5DigestAsHex((password).getBytes());
            if (userDetails.getPassword().equals(encodePassword)) {
                // 这里设置权限，后面就可以从userDetails获取getAuthorities()权限了
                ArrayList<GrantedAuthority> authorities = getUserAuthoritiesByUsername(userName);
                // 生成jwt令牌 这里令牌里面存入了:userName,password,authorities, 当然你也可以放其他内容
                //（如果别人获得了密钥，token会被成功解析，所以不建议放密码等敏感信息进去）
                return new UsernamePasswordAuthenticationToken(userName, password, authorities);
            } else {
                throw new BadCredentialsException("密码错误");
            }
        } else {
            throw new UsernameNotFoundException("用户不存在");
        }
    }

    /**
     * 是否可以提供输入类型的认证服务
     * <p>
     * 登录时，先执行JWTLoginFilter.attemptAuthentication，然后会进入该方法
     * 最后再执行CustomAuthenticationProvider.authenticate方法，具体认证
     *
     * @param authentication
     * @author 周恒
     * @date 20200120 16:46:37
     * @since v1.0
     */
    @Override
    public boolean supports(Class<?> authentication) {
        System.out.println("CustomAuthenticationProvider.supports");
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

    /**
     * 获取该用户所有的菜单权限
     *
     * @param username 用户名
     * @return 返回 array list 描述此返回参数
     * @author 周恒
     * @date 20200121 10:53:48
     * @since v1.0
     */
    private ArrayList<GrantedAuthority> getUserAuthoritiesByUsername(String username) {
        System.out.println("CustomAuthenticationProvider.getUserAuthoritiesByUsername");
        List<String> menuCodeList = sysUserMapper.findMenuCodeByUserName(username);
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>(menuCodeList.size());
        menuCodeList.forEach(menuCode -> grantedAuthorities.add(new GrantedAuthorityImpl(MenuConstants.ROLE_PREFIX + menuCode)));
        return grantedAuthorities;
    }

}
